public class Solution529 {

    int[] dx={-1,0,1,-1,0,1,-1,0,1};
    int[] dy={-1,-1,-1,0,0,0,1,1,1};

    public char[][] updateBoard(char[][] board, int[] click) {
        if (board[click[0]][click[1]]=='M'){
            board[click[0]][click[1]]='X';
        }else if (board[click[0]][click[1]]=='E'){
            int[][] visit=new int[board.length][board[0].length];
            for (int i=0;i<board.length;i++){
                for (int j=0;j<board[0].length;j++){
                    if (board[i][j]=='B' || board[i][j]>='1' && board[i][j]<='8'){
                        visit[i][j]=1;
                    }
                }
            }
            dfs(click[0],click[1],board,visit);
        }
        return board;
    }

    private void dfs(int x, int y, char[][] board, int[][] visit) {
        int count=0;
        visit[x][y]=1;
        for (int i=0;i<9;i++){
            int xx=x+dx[i];
            int yy=y+dy[i];
            if (valid(xx,yy,board.length,board[0].length) && board[xx][yy]=='M'){
                count++;
            }
        }
        if (count!=0){
            board[x][y]=(char)(count+'0');
        }else{
            board[x][y]='B';
            for (int i=0;i<9;i++){
                int xx=x+dx[i];
                int yy=y+dy[i];
                if (valid(xx,yy,board.length,board[0].length) && visit[xx][yy]==0){
                    dfs(xx,yy,board,visit);
                }
            }
        }
    }

    private boolean valid(int x, int y, int m, int n) {
        return x>=0 && y>=0 && x<m && y<n;
    }

    public static void main(String[] args) {
        char[][] board=new char[][]{{'E','E','E','E','E'},{'E','E','M','E','E'},{'E','E','E','E','E'},{'E','E','E','E','E'}};
        board=new Solution529().updateBoard(board,new int[]{3,0});
        for (char[] chars : board) {
            System.out.println(chars);
        }
    }
}
